<template>
  <div class="login-wrap">
    <div class="ms-login">
      <div class="ms-title">论文管理系统</div>
      <div class="login-register">
        <a-tabs class="demo-tabs" >
          <!--登录-->
          <a-tab-pane id="login" tab="登录" name="first" key="1">
            <el-form
                ref="loginForm"
                :model="loginForm"
                :rules="rules"
                label-width="80px"
                class="login"
                style="width: 80%;"
                @keyup.enter.native="submitForm('loginForm')"
            >
              <el-form-item label="帐号" prop="email">
                <el-input v-model="loginForm.email"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="loginForm.password" show-password></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm1('loginForm')">登录</el-button>
                <el-button @click="resetForm('loginForm')">重置</el-button>
              </el-form-item>
            </el-form>
          </a-tab-pane>
          <!--注册-->
          <a-tab-pane tab="注册" name="second" key="2">
            <el-form
                ref="registerForm"
                :model="registerForm"
                :rules="rules1"
                label-width="120px"
                class="demo-form-inline"
                status-icon
                style="max-width: 550px"

            >
              <!--用户名-->
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="registerForm.email"/>
              </el-form-item>

              <el-form-item label="验证码" prop="code">
                <div style="display: flex;width: 120%">
                  <el-input v-model="registerForm.code" style="width: 75%;justify-content: start"></el-input>
                  <el-button  id="sendCode" type="primary"
                              style="width: 25%;justify-content: end;text-align: center"
                              @click="getCode('registerForm')"
                  ><span v-show="show">获取验证码</span>
                    <span v-show="!show" class="count">{{count}}s后重新发送</span>
                  </el-button>

                  <!--                    http://139.196.160.103:8081/user/send?email=2775504008%40qq.com&type=1-->
                </div>
              </el-form-item>
              <el-form-item label="密码" prop="password1">
                <el-input v-model="registerForm.password1" type="password" show-password/>
              </el-form-item>
              <el-form-item label="重复密码" prop="password2">
                <el-input v-model="registerForm.password2" type="password" show-password/>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm2('registerForm')"
                >提交</el-button
                >
                <el-button @click="resetForm('registerForm')">重置</el-button>
              </el-form-item>
            </el-form>
          </a-tab-pane>

        </a-tabs>
      </div>


    </div>
  </div>
  j
</template>

<script>

import {ref} from "vue";
import { useRouter } from 'vue-router';
import axios from "axios";
import { usePermissStore } from '../store/permiss';
import {setToken} from "../utils/auth";
const permiss = usePermissStore();
const TIME_COUNT = 60;
const router=useRouter();
export default {
  data() {
    return {
      loginForm: {
        email: "",
        password: "",

      },
      registerForm: {
        email: "",
        code: "",
        password1: "",
        password2: "",

      },

      rules: {
        email: [
          {
            required: true,
            message: "Please input email address",
            trigger: "blur",
          },
          {
            type: "email",
            message: "Please input correct email address",
            trigger: ["blur", "change"],
          },
        ],
        password: [
          {
            required: true,
            message: "Please input password",
            trigger: "blur",
          },
        ],

      },
      rules1: {
        email: [
          {
            required: true,
            message: "邮箱不能为空",
            trigger: "blur",
          },
          {
            type: "email",
            message: "邮箱格式错误",
            trigger: ["blur", "change"],
          },
        ],
        password1: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            pattern: /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,20}$/,
            message: '密码必须同时包含字母、数字和特殊字符其中三项且8-20位'
          },
        ],
        password2: [
          {
            required: true,
            message: "请再次输入密码",
            trigger: "blur",
          },

        ],
        code: [{
          required: true,
          message: "请输入验证码",
          trigger: "blur",
        }],
      },
      activeKey: ref('1'),
      show: true,
      count: '',
      timer: null,
      coutrdown:60,
      inter:null,
    };
  },
  methods: {
    submitForm1(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //form表单不为空，valid为真
          // axios
          //   .post("https://partner.apptutti.com/api/partner/login",
          // .post("/api/partner/login",
          this.$http
              .get(`http://139.196.160.103:8081/user/loginByEmail?email=${this.loginForm.email}&password=${this.loginForm.password}`)
              .then((res) => {
                res = res.data;
                // console.log(res);
                if (res.code === 0) {
                  localStorage.setItem("Token", res.data.token);
                  localStorage.setItem('ID',res.data.sessionId);
                  localStorage.setItem('password',JSON.stringify(this.loginForm.password));
                  localStorage.setItem('email',this.loginForm.email);
                  console.log(this.loginForm.email);
                  // nnickname获取
                  this.$http.get(`user/info`,{
                    headers: {
                      'Content-Type': 'application/json',
                      'session': localStorage.getItem('ID'),
                    }
                  }).then(response=>{
                    localStorage.removeItem('nickname');
                    localStorage.setItem('nickname', response.data.data.nickname);
                    localStorage.setItem('phone',response.data.data.telephone);

                    console.log(response.data.data);
                    console.log(localStorage.getItem('nickname'));
                  })
                  if(res.data.sessionData.type===1)
                  {
                    localStorage.setItem('ms_username', 'admin');
                  }
                  else{
                    localStorage.setItem('ms_username', 'user');
                  }
                  localStorage.setItem('pic',res.data.sessionData.portrait);
                  console.log(localStorage.getItem('pic'));
                  const keys = permiss.defaultList[localStorage.getItem('ms_username')==='admin' ? 'admin' : 'user'];
                  permiss.handleSet(keys);
                  localStorage.setItem('ms_keys', JSON.stringify(keys));
                  setToken(res.data.token);
                  this.$router.push({name: "dashboard", path: "/dashboard"});
                  this.$message.success("登录成功!");
                } else {
                  //alert(res.msg);

                  this.$router.push("/");
                  this.$message.error("用户名或者密码错误！");
                  if (res.code === 401) {
                    //localStorage.removeItem("Token");
                    this.$router.push("/");
                  }
                }
              });
        } else {
          this.$message.error("邮箱格式不对！");
          return false;
        }
      });
    },
    submitForm2(formName) {
      this.$refs[formName].validate((valid) => {
        let emailReg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
        let passwordReg = /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,20}$/;
        if (this.registerForm.email === "" || this.registerForm.email === undefined || this.registerForm.email == null) {
          this.$message.error('邮箱不能为空');
        } else if (!emailReg.test(this.registerForm.email)) {
          this.$message.error('请输入正确的邮箱！');
        } else if (this.registerForm.code === "") {
          this.$message.error('验证码不能为空!')
        } else if (this.registerForm.password1 === "") {
          this.$message.error('请输入密码！');
        } else if (!passwordReg.test(this.registerForm.password1)) {
          this.$message.error('密码必须同时包含字母、数字和特殊字符其中三项且8-20位');
        } else if (this.registerForm.password2 === "") {
          this.$message.error('请再次输入密码！');
        }
            // else if(!this.checkCode('registerForm')){
            //
        // }
        else if ((this.registerForm.password1 === this.registerForm.password2)) {
          if (valid) {
            //form表单不为空，valid为真
            this.$http
                .get(`http://139.196.160.103:8081/user/check?code=${this.registerForm.code}&email=${this.registerForm.email}`)
                .then((res) => {
                  res = res.data;
                  if (res.code === 0 || res.code === 200) {
                  } else {
                    this.$message.error('验证码错误');
                    //return false;
                  }
                })
            this.$http
                .post(`http://139.196.160.103:8081/user/signUp?email=${this.registerForm.email}&password=${this.registerForm.password1}`)
                //.post('http://139.196.160.103:8081/user/signUp?email=${this.registerForm.email}&password=${this.registerForm.password}')
                // .post("/user/signUp", {
                //   email: JSON.stringify(this.registerForm.email),
                //   password: JSON.stringify(this.registerForm.password1),
                // })
                .then((res) => {
                  res = res.data;
                  if (res.code === 0 || res.code === 200) {
                    // localStorage.setItem('ms_username', this.loginForm.email);
                    // const keys = permiss.defaultList[this.loginForm.email == 'admin' ? 'admin' : 'user'];
                    // permiss.handleSet(keys);
                    // localStorage.setItem('ms_keys', JSON.stringify(keys));
                    this.$router.go("/");
                    this.$message.success("注册成功!");
                  } else {
                    // alert(res.msg);
                    this.$router.push("/");
                    this.$message.error("邮箱已经被注册");
                    if (res.code === 401) {
                      this.$router.push("/");
                    }
                  }
                });
          } else {
            this.$message.error("服务器请求失败，请检查网络！");
            return false;
          }
        } else {
          this.$message.error("两次输入的密码不一致");
          return false;
        }

      });
    },
    // http://139.196.160.103:8081/user/check?code=683798&email=2775504008%40qq.com
    // submitForm(formName) {
    //   this.$refs[formName].validate((valid) => {
    //     if (valid) {
    //       axios.get(`http://139.196.160.103:8081/user/loginByEmail?email=${this.loginForm.email}&password=${this.loginForm.password}`).then(res=>{
    //         if(res.status===200){
    //          // this.$router.push({path:'/dashboard'});
    //           localStorage.setItem('ms_username', this.loginForm.username);
    //           const keys = permiss.defaultList[this.loginForm.username == 'admin' ? 'admin' : 'user'];
    //           permiss.handleSet(keys);
    //           localStorage.setItem('ms_keys', JSON.stringify(keys));
    //           this.$router.push({name: "dashboard",path:"/dashboard"});
    //           this.$message.success("登录成功!");
    //         }
    //
    //       },error=>{
    //         console.log(error)
    //       })
    //     } else {
    //       this.$message.error("邮箱格式不对.");
    //       return false;
    //     }
    //   });
    // },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getCode(formName) {
      if (!this.timer) {
        if (this.registerForm.email === "") {
          this.$message.error('邮箱不能为空');
          return false;
        }
        this.$refs[formName].validate((valid) => {
          this.$http
              .get(`http://139.196.160.103:8081/user/send?email=${this.registerForm.email}&type=0`)
              .then((res) => {
                res = res.data;
                if (res.code === 0 || res.code === 200) {

                  //this.fusn();
                  this.$message.success('已发送验证码');
                  this.count = TIME_COUNT;
                  this.show = false;
                  this.timer = setInterval(() => {
                    if (this.count > 0 && this.count <= TIME_COUNT) {
                      this.count--;
                    } else {
                      this.show = true;
                      clearInterval(this.timer);
                      this.timer = null;
                    }
                  }, 1000)
                } else {
                  this.$message.error("该邮箱已被注册");
                }
              })
        })



      }
    },
    checkCode(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$http
              .get(`http://139.196.160.103:8081/user/check?code=${this.registerForm.code}&email=${this.registerForm.email}`)
              .then((res) => {
                res = res.data;
                if (res.code === 0 || res.code === 200) {
                  this.$message.success('验证码正确');
                } else {
                  this.$message.error('验证码错误');
                  //return false;
                }
              })
        } else {
          this.$message.error("服务器请求错误，请检查网络！");
          //return false;
        }
      });
    },
    toLoading(){ //短信验证码发送
      this.show=false;
      this.inter = setInterval(this.fusn, 1000);
    },
    fusn(){
      //let this=this;
      // console.log(this.coutrdown);
      this.coutrdown--;
      window.localStorage.setItem("X_no_time",this.coutrdown);//存入本地
      if(window.localStorage.getItem("X_no_time")<="0"){//等于0时清空
        window.localStorage.removeItem('X_no_time');
      }
      if(this.coutrdown <= 0) {//小于或者等于0时
        this.coutrdown=60;//重新赋值为60秒,如果用户在倒计时期间关闭了浏览器下次打开也面会调用created()方法
        clearInterval(this.inter);
        this.show=true;
      }


    },//fusn

  },//methods
  created(){//实例化完成后
    // let this=this;
    if(window.localStorage.getItem("X_no_time")==null){
      console.log("第一次或者又过来一次");
    }else{
      this.coutrdown=Number(window.localStorage.getItem("X_no_time"));
      this.toLoading()
    }

  },



};
</script>
<!--//  e.preventDefault();-->
<!--//调用验证码发送接口-->

<!--sendCode(this.email).then(-->
<!--res => {-->
<!--if (res.data.code === 0) {-->
<!--const toast = this.$createToast({-->
<!--txt: "发送成功",-->
<!--type: "correct",-->
<!--time: 1500-->
<!--});-->
<!--toast.show();-->
<!--}else if(res.data.code === 240002){-->
<!--const toast = this.$createToast({-->
<!--txt: "验证码发送过快，请稍后再试",-->
<!--type: "error",-->
<!--time: 1500-->
<!--});-->
<!--toast.show();-->
<!--}else if(res.data.code === 240001){-->
<!--const toast = this.$createToast({-->
<!--txt: "邮箱号不合法，请重输入",-->
<!--type: "error",-->
<!--time: 1500-->
<!--});-->
<!--toast.show();-->
<!--}else{-->
<!--const toast = this.$createToast({-->
<!--txt: "发送失败，请重试",-->
<!--type: "error",-->
<!--time: 1500-->
<!--});-->
<!--toast.show();-->
<!--}-->
<!--}-->
<!--);-->
<style scoped>
.login-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  background-image: url(../assets/img/login.svg);
  background-size: 100%;
}
.ms-title {
  width: 100%;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
  color: #000000;
  font-weight: bold;
  font-size: 25px;
  font-family: 微软雅黑;
}
.ms-login {
  position: absolute;
  left: 38%;
  top: 30%;
  width: 50%;
  margin: -190px 0 0 -175px;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.8);
  overflow: hidden;
}
.ms-content {
  padding: 30px 30px;
}
.login-btn {
  text-align: center;
}
.login-btn button {
  width: 50%;
  height: 36px;
  margin-bottom: 10px;
}
.login-tips {
  font-size: 12px;
  line-height: 30px;
  color: #fff;
}
.login-register{
  position: relative;
  width: 97%;
  left: 1.5%;
}

</style>
